<template>
  <div v-loading="loading">
    <el-button
      v-hasPermissions="['basic:system:menus:add']"
      type="primary"
      @click="expand"
      :icon="DCaret"
    >
      全部展开/折叠
    </el-button>
    <div class="invoice-list">
      <!-- 表头的值,自己单独写的 -->
      <ul class="invoice-header" style="margin-top: 0px">
        <li class="invoice-item">菜单名称</li>
        <li class="invoice-item">路由标识</li>
        <li class="invoice-item">菜单路径</li>
        <li class="invoice-item">类型</li>
        <li class="invoice-item">状态</li>
      </ul>
      <el-tree
        :key="keyValue"
        :props="prop"
        :data="tableData"
        show-checkbox
        check-strictly
        :default-expand-all="expandAll"
        node-key="id"
        :style="{ height: scrollerHeight, overflow: 'auto' }"
        ref="treeDataRef"
      >
        <!-- 使用自定义,需要加slot-scope,返回两个值,node是当前节点指定的对象
	        data是当前节点的数据 -->
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span class="table_info_node">
              <span class="table_info_item" style="width: 200">
                <span>{{ data.name }}</span>
                <!-- <span v-if="data.pid == 0">
                  【{{ formatDictCode('PT', data.platform) }}】
                </span> -->
              </span>
              <span class="table_info_item" style="text-align: left">
                {{ data.code }}
              </span>
              <span class="table_info_item" style="text-align: left">
                {{ data.component }}
              </span>
              <span class="table_info_item" style="text-align: center">
                {{ formatDictCode('SYS_CDLX', data.type) }}
              </span>
              <span class="table_info_item" style="text-align: center">
                <!-- {{ formatDictCode('ZT', data.status) }} -->
                {{ data.status == 1 ? '启用' : '停用' }}
              </span>
            </span>
          </div>
        </template>
      </el-tree>
    </div>
  </div>
  <div class="dialog-footer-btn">
    <el-button type="default" @click="emit('close')">取消</el-button>
    <el-button
      v-hasPermissions="['basic:system:roles:save']"
      type="primary"
      @click="Save"
      v-prevent-repeat-click
    >
      保存
    </el-button>
  </div>
</template>

<script setup>
import { Plus, DCaret } from '@element-plus/icons-vue'
import { formatDictCode } from '@/utils/index.js'
import { get_roles_bind, get_menus_bind } from '@/api/system'
import { findIndex } from 'lodash-es'
const emit = defineEmits(['close', 'submitForm'])
const props = defineProps({
  RoleId: String,
  platform: [String, Number]
})
const expandAll = ref(false)

const scrollerHeight = computed(() => {
  return window.innerHeight - 250 + 'px'
})
const keyValue = ref()
const prop = ref({
  children: 'children',
  label: 'name',
  id: 'id'
})
const searchForm = reactive({
  platform: ''
})

const state = reactive({})
const loading = ref(true)
const rolemenu = ref('')
const multipleSelection = ref([])
const tableData = ref([])
const treeDataRef = ref()
const expand = () => {
  expandAll.value = !expandAll.value
  keyValue.value = new Date().getTime()
  getList()
}

onMounted(() => {
  getList()
})

const loadClose = () => {
  loading.value = false
}

defineExpose({
  loadClose
})

/* const setIdNumberToString = data => {
  data.forEach(item => {
    item.id = item.id + ''
    if (item.children && item.children.length > 0) {
      setIdNumberToString(item.children)
    }
  })
  return data
} */

// tree组件渲染的数据列表
const getList = () => {
  searchForm.platform = props.platform
  searchForm.status = 1
  loading.value = true
  get_menus_bind(searchForm)
    .then(res => {
      if (res.succeed) {
        tableData.value = res.data
        get_roles_bind(props.RoleId)
          .then(result => {
            nextTick(() => {
              result.data.forEach(element => {
                const node = treeDataRef.value.getNode(element)
                console.log('node',node)
                // if (node && node.isLeaf) {
                  treeDataRef.value.setChecked(element, true)
                // }
              })
            })
            loading.value = false
          })
          .catch(error => {
            loading.value = false
          })
      }
    })
    .catch(err => {
      loading.value = false
    })
}

const getStateName = status => {
  if (status == 1) {
    return '启用'
  } else {
    return '停用'
  }
}

const getTypeName = type => {
  if (type == 1) {
    return '目录'
  } else if (type == 2) {
    return '页面'
  } else {
    return '按钮'
  }
}

const Save = () => {
  loading.value = true
  let res = treeDataRef.value
    .getCheckedKeys()
    .concat(treeDataRef.value.getHalfCheckedKeys())

  state.roleId = props.RoleId
  state.resId = res.join(',')
  emit('submitForm', state)
}
let ids = []
const formatArr = val => {
  console.log(val)
  for (let i = 0; i < val.length; i++) {
    ids.push(val[i].id)
    if (val[i].children.length > 0) {
      formatArr(val[i].children)
    }
  }
  return ids
}

const handleCheckChange = (curObj, objStatus, indeterminate) => {
  // console.log(curObj)
  console.log(objStatus.checkedKeys)
  let ids = objStatus.checkedKeys
  if (ids.findIndex(item => item == curObj.id) != -1) {
    // 新增
    console.log('新增');
    if (curObj.children.length > 0) {
      let arr = formatArr(curObj.children)

      for (let i = 0; i < arr.length; i++) {
        if (ids.indexOf(arr[i]) != -1) {
        } else {
          ids.push(arr[i])
        }
      }

      treeDataRef.value.setCheckedKeys(ids, false)
    }
  } else {
    console.log('取消');
    // 取消
    if (curObj.children.length > 0) {
      let arr = formatArr(curObj.children)
      for (let i = 0; i < arr.length; i++) {
        ids.splice(ids.indexOf(arr[i]), 1)
      }
      treeDataRef.value.setCheckedKeys(ids, false)
    }
  }
}

const checkChange = (a, b, c) => {
  console.log(a, b, c)
  b ? findchildren(a, b) : ''
}

const findchildren = current => {
  treeDataRef.value.setChecked(current.id, true, true)
  let d = current.children
  if (d.length > 0) {
    d.forEach(a => {
      findchildren(a)
    })
  }
}
</script>

<style scoped lang="scss">
/* 弹窗提交时loading样式需占满整个弹窗 */
.el-loading-parent--relative {
  position: inherit !important;
}
.invoice-list {
  /* border: 1px solid #ebeef5; */
  margin-top: 10px;
}

.el-tree-node__children {
}

.invoice-header {
  background-color: #f4f9ff;
  display: flex;
  padding-left: 0px;
  border-bottom: 1px solid #ebeef5;
}

.invoice-item {
  list-style: none;
  padding: 10px;
  padding-right: 0;
  flex: 1;

  padding-left: 20px;
  list-style: none;
  text-align: center;
}

:deep(.el-tree-node__content) {
  background: #f2f2f2;
  height: 40px;
}

:deep(.el-tree-node__content) {
  background: #fff;
}

.custom-tree-node {
  width: 100%;
  height: 100%;
}

.total_info_box {
  background: #f2f2f2;
  line-height: 40px;

  span {
    float: left;
    font-size: 12px;
    margin: 0 15px;

    i {
      display: inline-block;
      margin-right: 3px;
    }
  }
}

.table_info_node {
  display: flex;
  height: 100%;
}

.table_info_item {
  flex: 1;
  height: 100%;
  padding-left: 10px;
  line-height: 40px;
}
:deep(.el-tree-node__label) {
  width: 100%;
}
</style>
